<template>
  <el-card class="box-card">
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" >
          <el-form-item  label="服务ID" style="margin-left: 50px">
            <el-input v-model="formParam.user" placeholder="服务ID"></el-input>
          </el-form-item>
          <el-form-item  label="访问路径" style="margin-left: 50px">
            <el-input v-model="formParam.region" placeholder="访问路径"></el-input>
          </el-form-item>
          <el-form-item style="margin-left: 50px">
            <el-button type="success" icon="el-icon-search" @click="getlist()">查询</el-button>
          </el-form-item>
          <el-form-item style="margin-left: 20px">
            <el-button type="success" icon="el-icon-star-off" @click="onReset()">重置</el-button>
          </el-form-item>
          <el-form-item style="margin-left: 20px">
            <el-button type="primary" icon="el-icon-circle-plus-outline" @click="onAdd('form')">新建</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-dialog v-if="createClick"  title="网关管理" :visible.sync="createClick" :close-on-click-modal="false" :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
        <el-form-item prop="id" v-show="false">
          <el-col :span="4">网关ID :</el-col>
          <el-col :span="8"><el-input v-model="form.id" :disabled="true"></el-input></el-col>
          <el-col :span="10"></el-col>
        </el-form-item>
        <el-form-item prop="serviceUri">
          <el-col :span="4">转发类型 :</el-col>
          <el-col :span="14">
            <el-radio-group v-model="form.serviceUriType">
              <el-radio-button label="lb://" title="标识配置的转发地址为注册中心服务ID"></el-radio-button>
              <el-radio-button label="http://" title="标识配置的转发地址http请求"></el-radio-button>
              <el-radio-button label="https://" title="标识配置的转发地址https请求"></el-radio-button>
            </el-radio-group>
          </el-col>
          <el-col :span="6"></el-col>
        </el-form-item>
        <el-form-item prop="serviceUri" title="配置服务地址，lb开头为注册中心服务请求转发">
          <el-col :span="4">转发地址 :</el-col>
          <el-col :span="14">
            <el-input placeholder="服务地址" v-model="form.serviceId">
              <template slot="prepend" style="width:20px">{{form.serviceUriType}}</template>
            </el-input>
          </el-col>
          <el-col :span="6"></el-col>
        </el-form-item>
        <el-form-item prop="predPath" title="请求路径的匹配规则，多个参数用逗号隔开，如：/aa/**,/bb/**">
          <el-col :span="4">请求路径 :</el-col>
          <el-col :span="14">
            <el-input placeholder="多个参数用逗号隔开" v-model="form.predPath"></el-input>
          </el-col>
          <el-col :span="6"></el-col>
        </el-form-item>
        <el-form-item title="路径前缀删除，如：配置 2 ，请求/name/bar/foo，去除掉前面两个前缀之后，最后转发到目标服务的路径为/foo">
          <el-col :span="4">前缀删除:</el-col>
          <el-col :span="14">
            <el-input-number size="mini" v-model="form.filterStripPrefix" min="0"></el-input-number>
          </el-col>
          <el-col :span="6"></el-col>
        </el-form-item>
        <el-collapse accordion>
          <el-collapse-item name="1">
            <template slot="title">
              <el-divider content-position="center" >高级设置</el-divider>
            </template>

            <el-form-item size="small" style="font-weight: bold" title="配置路由匹配请求的规则">
              <el-col :span="4">Predicates:</el-col>
              <el-col :span="20"></el-col>
            </el-form-item>
            <el-form-item prop="predCookie" title="配置对Cookie中值的匹配，第一个为key，第二个为value，如：chocolate,ch.p">
              <el-col :span="4":offset="1">Cookie:</el-col>
              <el-col :span="13">
                <el-input placeholder="Cookie中值的匹配" v-model="form.predCookie"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="predHeader" title="匹配Http请求头信息，第一个为key，第二个为value是正则表达式；如：X-Request-Id,\d+">
              <el-col :span="4":offset="1">请求头:</el-col>
              <el-col :span="13">
                <el-input placeholder="匹配Http请求头" v-model="form.predHeader"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="predHost" title="匹配Http请求Host, 如：**.somehost.com">
              <el-col :span="4":offset="1">请求Host:</el-col>
              <el-col :span="13">
                <el-input placeholder="Http请求Host过滤" v-model="form.predHost"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="predMethod" title="匹配Http请求方法，如：GET">
              <el-col :span="4":offset="1">请求方法:</el-col>
              <el-col :span="13">
                <el-input placeholder="Http请求方法过滤" v-model="form.predMethod"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="predQuery" title="匹配Http请求中的查询参数，第一个为key，第二个为value是正则表达式可省略，如：param1,value">
              <el-col :span="4":offset="1">查询参数:</el-col>
              <el-col :span="13">
                <el-input placeholder="Http请求中的查询参数过滤" v-model="form.predQuery"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="predRemoteAddr" title="匹配请求中的RemoteAddr，即请求IP地址过滤，如：192.168.1.1/24">
              <el-col :span="4":offset="1">IP过滤:</el-col>
              <el-col :span="13">
                <el-input placeholder="Http请求中的RemoteAddr过滤" v-model="form.predRemoteAddr"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="predAfter" title="设置时间之后可以访问，如：2020-01-20T17:42:47.789-08:00[Asia/Shanghai]">
              <el-col :span="4":offset="1">After:</el-col>
              <el-col :span="13">
                <el-input placeholder="设置指定时间之后可以访问" v-model="form.predAfter"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="predBefore" title="设置时间之前可以访问， 如：2020-01-20T17:42:47.789-08:00[Asia/Shanghai]">
              <el-col :span="4":offset="1">Before:</el-col>
              <el-col :span="13">
                <el-input placeholder="设置指定时间之后可以访问" v-model="form.predBefore"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="predWeight" title="至少两组以上路由可以配置权重路由，配置后会根据权重随机访问几个路由，第一个参数为组名称，第二个参数标识权重值，如：service1,80">
              <el-col :span="4":offset="1">路由权重:</el-col>
              <el-col :span="13">
                <el-input placeholder="权重路由过滤" v-model="form.predWeight"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>


            <el-form-item size="small" style="font-weight: bold" title="配置路由过滤器规则">
              <el-col :span="4">Filters:</el-col>
              <el-col :span="20"></el-col>
            </el-form-item>
            <el-form-item prop="filterRewritePath" title="路径重写，如：/path/(?<segment>.*), /$\{segment}">
              <el-col :span="4":offset="1">路径重写:</el-col>
              <el-col :span="13">
                <el-input placeholder="包含两个参数，以逗号分隔" v-model="form.filterRewritePath"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterAddRequestHeader" title="修改请求头，包含两个参数，以逗号分隔，第二个参数可忽略，如：key,value">
              <el-col :span="4":offset="1">请求头:</el-col>
              <el-col :span="13">
                <el-input placeholder="包含两个参数，以逗号分隔" v-model="form.filterAddRequestHeader"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterAddRequestParameter" title="修改请求参数，包含两个参数，以逗号分隔，第二个参数可忽略，如：key,value">
              <el-col :span="4":offset="1">请求参数:</el-col>
              <el-col :span="13">
                <el-input placeholder="包含两个参数，以逗号分隔，第二个参数可忽略" v-model="form.filterAddRequestParameter"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterAddResponseHeader" title="修改响应参数，包含两个参数，以逗号分隔，第二个参数可忽略，如：key,value">
              <el-col :span="4":offset="1">响应头:</el-col>
              <el-col :span="13">
                <el-input placeholder="包含两个参数，以逗号分隔，第二个参数可忽略" v-model="form.filterAddResponseHeader"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterPrefixPath" title="路径前缀增强，如：配置/mypath后，请求路径/hello将会被替换为 /mypath/hello">
              <el-col :span="4":offset="1">路径前缀:</el-col>
              <el-col :span="13">
                <el-input placeholder="路径片段，无需*匹配" v-model="form.filterPrefixPath"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterPreserveHostHeader" title="请求携带保留原始Host，只能是0和1其中一个值">
              <el-col :span="4":offset="1">原始Host:</el-col>
              <el-col :span="13">
                <el-input placeholder="只能为0和1其中一个" v-model="form.filterPreserveHostHeader"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterRedirectTo" title="重定向，两个参数：状态码（3**），网址，如：302,http://acme.org表示302请求时自动重定向到http://acme.org地址">
              <el-col :span="4":offset="1">重定向:</el-col>
              <el-col :span="13">
                <el-input placeholder="两个参数：状态码，网址" v-model="form.filterRedirectTo"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterHystrixArgName" title="断路器熔断器名称，手动输入，如（默认）：fallbackcmd">
              <el-col :span="4":offset="1">断路器名称:</el-col>
              <el-col :span="13">
                <el-input placeholder="默认为fallbackcmd" v-model="form.filterHystrixArgName"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterHystrixFallbackUri" title="断路器重定向地址，如：forward:/incaseoffailureusethis标识请求熔断后默认转发到/incaseoffailureusethis地址">
              <el-col :span="4":offset="1">断路器地址:</el-col>
              <el-col :span="13">
                <el-input placeholder="forward:+转发地址" v-model="form.filterHystrixFallbackUri"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterRequestRateLimiterKeyResolver" title="请求限流 - 键的解析器的 Bean 对象的名字。它使用 SpEL 表达式根据#{@beanName}从 Spring 容器中获取 Bean 对象；<请求限流三个项目需要同时为空或同时不为空>">
              <el-col :span="4":offset="1">限流解析器:</el-col>
              <el-col :span="13">
                <el-input placeholder="#{@SpringBeanName}" v-model="form.filterRequestRateLimiterKeyResolver"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterRequestRateLimiterReplenishRate" title="请求限流 - 令牌桶每秒填充平均速率，填充正整数，表示每秒增加允许的请求数量；<请求限流三个项目需要同时为空或同时不为空>">
              <el-col :span="4":offset="1">限流秒增数:</el-col>
              <el-col :span="13">
                <el-input placeholder="正整数" v-model="form.filterRequestRateLimiterReplenishRate"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterRequestRateLimiterBurstCapacity" title="请求限流 - 令牌桶总容量，填充正整数，表示当前可用请求池大小，请求数量大于请求池大小时会熔断；<请求限流三个项目需要同时为空或同时不为空>">
              <el-col :span="4":offset="1">限流总数量:</el-col>
              <el-col :span="13">
                <el-input placeholder="正整数" v-model="form.filterRequestRateLimiterBurstCapacity"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterRemoveRequestHeader" title="删除请求头属性，如：HeaderKey">
              <el-col :span="4":offset="1">移除请求头:</el-col>
              <el-col :span="13">
                <el-input placeholder="请求头的Key名称" v-model="form.filterRemoveRequestHeader"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterRemoveResponseHeader" title="删除响应头属性，如：HeaderKey">
              <el-col :span="4":offset="1">移除响应头:</el-col>
              <el-col :span="13">
                <el-input placeholder="响应头的Key名称" v-model="form.filterRemoveResponseHeader"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterRewriteResponseHeader" title="重写响应头，如：X-Response-Foo,password=[^&]+,password=***，将请求 /42?user=ford&password=omg!what&flag=true, 改为 /42?user=ford&password=***&flag=true">
              <el-col :span="4":offset="1">重写响应头:</el-col>
              <el-col :span="13">
                <el-input placeholder="响应头的Key名称" v-model="form.filterRewriteResponseHeader"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterSetPath" title="重设请求路径，如：/{segment}，请求/foo/bar，在接下来的处理中被改为/bar">
              <el-col :span="4":offset="1">重写路径:</el-col>
              <el-col :span="13">
                <el-input placeholder="路径片段，无需*匹配" v-model="form.filterSetPath"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterSetResponseHeader" title="设置响应头，如：X-Request-Foo,Bar修改响应头X-Response-Foo为Bar">
              <el-col :span="4":offset="1">重写响应头:</el-col>
              <el-col :span="13">
                <el-input placeholder="以逗号分隔两个参数：HeaderKey,value" v-model="form.filterSetResponseHeader"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterSetStatus" title="设置Http状态">
              <el-col :span="4":offset="1">重写状态码:</el-col>
              <el-col :span="13">
                <el-input placeholder="Http请求状态码，正整数" v-model="form.filterSetStatus"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterRequestSize" title="设置文件传输大小">
              <el-col :span="4":offset="1">文件大小:</el-col>
              <el-col :span="13">
                <el-input placeholder="文件传输大小，正整数" v-model="form.filterRequestSize"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
            <el-form-item prop="filterRetry" title="失败重试次数">
              <el-col :span="4":offset="1">重试次数:</el-col>
              <el-col :span="13">
                <el-input placeholder="失败重试次数，正整数" v-model="form.filterRetry"></el-input>
              </el-col>
              <el-col :span="6"></el-col>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
        <el-form-item>
          <el-row style="float:right" >
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="onCancel()">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <template>
      <el-table
        :data="list"
        style="width: 100%"
        stripe=true
        border=true
        size="mini"
        height="400"
        highlight-current-row=true
        :row-class-name="tableRowClassName">
        <el-table-column
          type="index"
          label="序号"
          width="60"
          align="center">
        </el-table-column>
        <el-table-column
          prop="id"
          label="网关ID"
          width="150">
        </el-table-column>
        <el-table-column
          prop="serviceUri"
          label="转发地址"
          width="180">
        </el-table-column>
        <el-table-column
          prop="predPath"
          label="请求地址"
          width="180">
        </el-table-column>
        <el-table-column
          prop="filterStripPrefix"
          label="前缀移除"
          width="80"
          align="center">
        </el-table-column>
        <el-table-column
          prop="filterPrefixPath"
          label="前缀增强"
          header-align="center">
        </el-table-column>
        <el-table-column
          prop="filterHystrixFallbackUri"
          label="断路器重定向">
        </el-table-column>
        <el-table-column
          prop="filterSetPath"
          label="状态"
          width="100"
          align="center">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.routeStatus==='1'?'success':'warning'"
              disable-transitions>{{scope.row.remarks}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="cz"
          label="操作"
          width="180"
          align="center">
          <template slot-scope="scope">
            <el-button-group>
              <el-button type="primary" size="mini" round=true icon="el-icon-edit"
                         title="路由编辑"
                         @click="onEdit(scope.row)"></el-button>
<!--              <el-button type="info" size="mini" round="true" icon="el-icon-switch-button"-->
<!--                         title="禁用"-->
<!--                         @click="onDelect(scope.row)"></el-button>-->
              <el-button type="danger" size="mini" round=true icon="el-icon-delete"
                         title="删除"
                         @click="onDelect(scope.row)"></el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

    </template>
  </el-card>
</template>

<script>
    import {list, add, update,save, del} from '@/api/gateway/index'
    import {validateServiceUri, validatePredPath} from './validate.js'

    export default {
        data() {
            return {
                type:false,
                createClick:false,
                form:{},
                rules: {
                    id: [
                        { required: true, message: '请填写网关ID', trigger: 'blur' }
                    ],
                    serviceUri: [
                        { validator: validateServiceUri, trigger: 'blur' }
                    ],
                    predPath: [
                        { required: true, message: '转发地址不能为空', trigger: 'blur' },
                        { validator: validatePredPath, trigger: 'blur' }
                    ]
                },
                formParam: {
                    user: '',
                    region: ''
                },
                list: [],
            }
        },
        watch: {
            'form.serviceId': {
                handler(newName, oldName) {
                    this.form.serviceUri = this.form.serviceUriType+newName;
                },
                immediate: true
            },
            'form.serviceUriType': {
                handler(newName, oldName) {
                    this.form.serviceUri = newName+this.form.serviceId;
                },
                immediate: true
                // deep: true
            }
        },
        created(){
            this.getlist()
        },
        methods: {
            onReset(){
                this.formParam.user='',
                this.formParam.region=''
                this.getlist()
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        this.initFormData();
                        this.getlist()
                        done();
                    })
                    .catch(_ => {});
            },
            getlist(){
                list(this.formParam).then(res => {
                    this.list= res.data
                }).catch((err) => {
                    this.$message.error(err);
                })
            },
            //添加
            onAdd(){
                this.initFormData();
                this.createClick=true
            },
            //编辑
            onEdit(row){
                console.log(row);
                this.form=row;
                var validNum = this.form.serviceUri.indexOf('://');
                if(validNum>0) {
                    this.form.serviceUriType = this.form.serviceUri.substring(0, validNum+3)
                }
                this.form.simplyed = false;
                this.createClick=true;

            },
            //保存
            onSubmit() {
                save(this.form).then(res => {
                    this.$message({
                        offset:'300',
                        message: '保存成功！',
                        type: 'success'
                    });
                    this.getlist()
                    this.onCancel()
                }).catch((err) => {
                    this.$message.error('保存失败');
                    this.getlist()
                    this.onCancel()
                })
            },
            //取消
            onCancel(){
                this.initFormData();
                this.createClick=false
            },
            //删除
            onDelect(row){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    del(row.id).then(res => {
                        this.$message({
                            offset:'300',
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getlist()
                    }).catch((err) => {
                        this.$message.error(err);
                    })
                }).catch(() => {
                    this.$message({
                        offset:'300',
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            onRefresh(){
                this.$http.post('/jbdp-route/query?serviceId='+this.formParam.user+"&routePath="+this.formParam.region,)
                    .then(res => {
                        this.list= res.data
                    }).catch((err) => {
                        this.$message.error(err);
                    })
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            advancedSetting() {
                // this.$message.info(""+this.form.simplyed);
                if(this.form.simplyed) {
                    this.form.simplyed = false;
                } else {
                    this.form.simplyed = true;
                }
            },
            initFormData() {
                this.form = {
                    id: '',
                    serviceId: '',
                    serviceUriType: 'lb://',
                    serviceUri: '',
                    routeOrder: 0,
                    remarks: '',
                    routeStatus: '1',
                    routeDBStatus: '0',
                    predPath: '',
                    predCookie: '',
                    predHeader: '',
                    predHost: '',
                    predMethod: '',
                    predQuery: '',
                    predRemoteAddr: '',
                    predAfter: '',
                    predBefore: '',
                    predWeight: '',
                    filterRewritePath: '',
                    filterAddRequestHeader: '',
                    filterAddRequestParameter: '',
                    filterAddResponseHeader: '',
                    filterPrefixPath: '',
                    filterStripPrefix: '1',
                    filterPreserveHostHeader: '',
                    filterRedirectTo: '',
                    filterHystrixArgName: '',
                    filterHystrixFallbackUri: '',
                    filterRequestRateLimiterKeyResolver: '',
                    filterRequestRateLimiterReplenishRate: '',
                    filterRequestRateLimiterBurstCapacity: '',
                    filterRemoveRequestHeader: '',
                    filterRemoveResponseHeader: '',
                    filterRewriteResponseHeader: '',
                    filterSetPath: '',
                    filterSetResponseHeader: '',
                    filterSetStatus: '',
                    filterRequestSize: '',
                    filterRetry: '',
                    simplyed: true
                }
            }
        }
    }
</script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>
